import axios from 'axios'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'

// API基础URL
const baseUrl = 'http://localhost:8000'

// 创建axios实例
const api = axios.create({
  baseURL: baseUrl,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 在发送请求之前做些什么
    return config
  },
  error => {
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    // 对响应数据做点什么
    return response.data
  },
  error => {
    // 对响应错误做点什么
    if (error.response) {
      // 服务器返回了错误状态码
      const status = error.response.status
      const data = error.response.data

      if (status === 400) {
        ElMessage.error(data.detail || '请求参数错误')
      } else if (status === 404) {
        ElMessage.error(data.detail || '请求的资源不存在')
      } else if (status === 500) {
        ElMessage.error('服务器内部错误')
      } else {
        ElMessage.error(`请求失败: ${status}`)
      }
    } else if (error.request) {
      // 请求已发出，但没有收到响应
      ElMessage.error('服务器无响应')
    } else {
      // 请求配置有误
      ElMessage.error(`请求错误: ${error.message}`)
    }
    return Promise.reject(error)
  }
)

/**
 * 通用API请求Hook
 */
export function useApi<T>(url: string) {
  const data = ref<T | null>(null)
  const loading = ref(false)
  const error = ref<Error | null>(null)

  // 获取数据
  const fetchData = async (params?: any) => {
    loading.value = true
    error.value = null
    
    try {
      const response = await api.get(url, { params })
      data.value = response
      return response
    } catch (err) {
      error.value = err as Error
      return null
    } finally {
      loading.value = false
    }
  }

  // 创建数据
  const createData = async (payload: any) => {
    loading.value = true
    error.value = null
    
    try {
      const response = await api.post(url, payload)
      return response
    } catch (err) {
      error.value = err as Error
      return null
    } finally {
      loading.value = false
    }
  }

  // 更新数据
  const updateData = async (id: string | number, payload: any) => {
    loading.value = true
    error.value = null
    
    try {
      const response = await api.put(`${url}/${id}`, payload)
      return response
    } catch (err) {
      error.value = err as Error
      return null
    } finally {
      loading.value = false
    }
  }

  // 删除数据
  const deleteData = async (id: string | number) => {
    loading.value = true
    error.value = null
    
    try {
      const response = await api.delete(`${url}/${id}`)
      return response
    } catch (err) {
      error.value = err as Error
      return null
    } finally {
      loading.value = false
    }
  }

  return {
    data,
    loading,
    error,
    fetchData,
    createData,
    updateData,
    deleteData
  }
}

// 导出API实例
export { api } 